package com.it.interceptor;

import com.it.context.BaseContext;
import com.it.properties.JwtProperties;
import com.it.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 验证JWT令牌
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 判断当前请求是否为方法请求
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 获取JWT令牌
        String token = request.getHeader(jwtProperties.getTokenName());
        
        log.info("请求路径: {}", request.getRequestURI());
        log.info("JWT令牌: {}", token);

        try {
            log.info("正在验证JWT令牌...");
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            Long userId = Long.valueOf(claims.get("userId").toString());
            log.info("解析出的用户ID：{}", userId);
            BaseContext.setCurrentId(userId);
            log.info("已将用户ID设置到BaseContext: {}", BaseContext.getCurrentId());
            return true;
        } catch (Exception e) {
            log.error("JWT令牌验证失败: {}", e.getMessage());
            response.setStatus(401);
            return false;
        }
    }
}
